import pandas as pd
import requests
import os
import time
# from comment.get_sanyaosu import get_sanyaosu


def fetch_and_save_appointment_data(ip,cookie,ysdm,ksdm,jigouma,output_file,xiancheng_num):
    url = f'{ip}/cis/psiregregisters/queryByConditions?t={str(time.time()).replace(".","")[0:13]}'

    headers = {
        "accept": "application/json",
        "cookie": f"JSESSIONID={cookie}",
    }

    today = time.strftime("%Y-%m-%d", time.localtime())
    print(ksdm,ysdm,jigouma)
    data = {
        "deptId": int(ksdm),
        "doctorId": ysdm,
        "endDate": f"{today} 23:59:59",
        "orgCode": jigouma,
        "startDate": f"{today} 00:00:00",
        "state": 1,
        "type": 4,
    }

    # 检查文件是否已存在
    if os.path.exists(output_file):
        # 读取Excel，默认第一行为表头
        df_existing = pd.read_excel(output_file)

    else:
        columns = ["姓名", "患者唯一标识符", "注册编号", "科室", "预约号别"]
        df_existing = pd.DataFrame(columns = columns)


    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 解析JSON响应
        json_data = response.json()

        # 创建一个列表用于存储提取的数据
        extracted_data = []
        print(json_data)
        # 遍历JSON数据中的每一条记录
        for item in json_data:
            # 提取需要的字段
            name = item.get("patientName")
            code = item.get("patientCode")
            reg_number = item.get("registerNumber")
            keshi = item.get("deptName")
            yvyuehaobie = item.get("regType")

            # 将提取的字段添加到列表中，形成一行数据
            extracted_data.append([name, code, reg_number, keshi,yvyuehaobie])

        # 创建DataFrame，设置表头
        df_new = pd.DataFrame(extracted_data, columns=["姓名", "患者唯一标识符", "注册编号", "科室","预约号别"])
        if len(df_existing) <= 1:
            # 将数据保存到Excel文件
            df_new.to_excel(output_file, index=False)
            print(f"{xiancheng_num}:数据已成功保存到 {output_file}")
            return True
        else:
            # 合并现有数据和新数据，然后按unique_keys去重，保留第一次出现的数据（即Excel中的数据）
            combined = pd.concat([df_existing, df_new], ignore_index=True)
            # 去重：keep="first"表示保留第一次出现的（Excel中已有的），删除后续重复的（新数据中的重复项）
            df_combined = combined.drop_duplicates(subset="姓名", keep="first")
            new_rows_count = len(df_combined) - len(df_existing)
            if new_rows_count <= 0:
                print(f"{xiancheng_num}无新数据可追加（全部重复）")
                return True
            df_to_append = df_combined.tail(new_rows_count)  # 取最后新增的行
            with pd.ExcelWriter(output_file, engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
                # 从Excel最末行开始写入（跳过原有数据和表头）
                # startrow = 原有数据行数 + 表头行（1行）
                startrow = writer.sheets["Sheet1"].max_row  # 自动获取当前最大行（最末行）
                df_to_append.to_excel(writer, sheet_name="Sheet1", startrow=startrow, header=False, index=False)

            print(f"{xiancheng_num}成功追加 {new_rows_count} 条新数据")
            return True
    except requests.RequestException as e:
        # raise e
        print(f"{xiancheng_num}:请求失败: {e}")
        return False
    except Exception as e:
        with open(f"执行结果/错误信息{xiancheng_num}.txt", 'a', encoding='utf-8') as f:
            f.write(f"{xiancheng_num}:处理数据时出错: {e}")
        print(f"{xiancheng_num}:处理数据时出错: {e}")
        return False


# 使用示例
if __name__ == "__main__":
    ip = "http://192.168.10.55:8080"
    cookie = "0317A86542F144C762AE185AD8D64CC3"
    ysdm, ksdm, jigouma = "66055", "7689", "1206"
    # try:
    #     ysdm, ksdm, jigouma = get_sanyaosu(ip,cookie)
    # except Exception as e:
    #     print(f"获取三要素时失败: {e}")
    #     exit()
    xiancheng_num = 1
    output_file = "执行结果/复诊预约人员统计.xlsx"

    file_exist = fetch_and_save_appointment_data(ip,cookie,ysdm,ksdm,jigouma,output_file,xiancheng_num)


